<template>
  <div class="page-wrap">
    <el-form label-width="80px" inline>
      <el-form-item label="班级名称:">
        <el-input
          placeholder="请输入搜索内容"
          prefix-icon="el-icon-search"
          v-model.trim="search.cls_name"
          @input.native="delayGetClass"
        ></el-input>
      </el-form-item>
      <el-form-item label="班级专业:">
        <el-select v-model="search.cls_dic_id_major" @change="getClass(true)">
          <el-option label="- 所有专业 -" :value="0"> </el-option>
          <el-option
            v-for="(item, index) in dictionary.filter(
              (category) => category.dic_group_key === 'class_major'
            )"
            :key="index"
            :label="item.dic_name"
            :value="item.dic_id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级状态:">
        <el-select v-model="search.cls_status" @change="getClass(true)">
          <el-option
            v-for="(item, index) in allStatus"
            :key="index"
            :label="item.name"
            :value="item.cls_status"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="btn-wrap">
        <el-button type="success" icon="el-icon-plus" @click.native="beforeAdd"
          >新增</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="classList"
      style="width: 100%"
      border
      stripe
      highlight-current-row
    >
      <el-table-column label="#" width="50" align="center" type="index">
      </el-table-column>
      <el-table-column label=" 班级名称" align="center" width="120">
        <template slot-scope="{ row }">
          <span>
            {{ row.cls_name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="班级专业" align="center" width="120">
        <template slot-scope="{ row }">
          <span>
            {{
              dictionary.length
                ? dictionary.find(
                    (item) => item.dic_id === row.cls_dic_id_major
                  ).dic_name
                : ""
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="教学老师" align="center" width="120">
        <template slot-scope="{ row }">
          <span>
            {{
              staffList.length
                ? staffList.find(
                    (item) => item.stf_id === row.cls_stf_id_teacher
                  ).stf_name
                : ""
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="教务老师" align="center" width="120">
        <template slot-scope="{ row }">
          <span>
            {{
              staffList.length
                ? staffList.find((item) => item.stf_id === row.cls_stf_id_admin)
                    .stf_name
                : ""
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="就业老师" align="center" width="120">
        <template slot-scope="{ row }">
          <span>
            {{
              staffList.length
                ? staffList.find((item) => item.stf_id === row.cls_stf_id_job)
                    .stf_name
                : ""
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="教室" align="center" width="120">
        <template slot-scope="{ row }">
          <span>
            {{
              classroomList.length && classList.length
                ? classroomList.find((item) => item.clsr_id === row.cls_clsr_id)
                  ? classroomList.find(
                      (item) => item.clsr_id === row.cls_clsr_id
                    ).clsr_name
                  : ""
                : ""
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="开课时间" align="center" width="120">
        <template slot-scope="{ row }">
          <span>
            {{ row.cls_begin }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="结课时间" align="center" width="120">
        <template slot-scope="{ row }">
          <span>
            {{ row.cls_end }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="班级状态" align="center" width="120">
        <template slot-scope="{ row }">
          <span v-if="row.cls_begin && row.cls_end" style="color :#ccc;">
            {{ "结课" }}
          </span>
          <span v-else-if="row.cls_begin && !row.cls_end" style="color :green;">
            {{ "开课中" }}
          </span>
          <span v-else style="color :orange;">
            {{ "未开课" }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" width="120">
        <template slot-scope="{ row }">
          <span :class="{ noRemark: !row.cls_remark }">
            {{ row.cls_remark ? row.cls_remark : "暂无相关备注" }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-edit"
            type="primary"
            size="mini"
            @click="beginUpdate(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            v-show="!scope.row.cls_begin && !scope.row.cls_end"
            icon="el-icon-edit"
            type="success"
            size="mini"
            @click.native="beginClass(scope.$index, scope.row)"
            >开课</el-button
          >
          <el-button
            v-show="scope.row.cls_begin && !scope.row.cls_end"
            icon="el-icon-edit"
            type="danger"
            size="mini"
            @click.native="endClass(scope.$index, scope.row)"
            >结课</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <!-- 分页 -->
    <el-pagination
      background
      layout="prev, pager, next,jumper,->,sizes,total"
      :total="pagination.total"
      :page-sizes="[5, 8, 10, 12, 15]"
      :page-size.sync="pagination.pageSize"
      :current-page.sync="pagination.currentPage"
      @current-change="getClass(false)"
      @size-change="getClass(true)"
    >
    </el-pagination>
    <!-- 新增编辑 -->
    <el-dialog :visible.sync="editor.isEditor" width="40%" :modal="false">
      <p slot="title" class="title" :class="{ active: editor.isMode }">
        班级维护-{{ editor.isMode ? "新增" : "修改" }}
      </p>
      <el-form
        label-width="80px"
        ref="ruleForm"
        :model="editor.mode"
        :rules="editor.rules"
        status-icon
      >
        <el-form-item label="班级名称" prop="cls_name">
          <el-input
            v-model.trim="editor.mode.cls_name"
            placeholder="请输入班级的名字"
          ></el-input>
        </el-form-item>
        <el-form-item label="班级专业" prop="cls_dic_id_major">
          <el-select
            v-model="editor.mode.cls_dic_id_major"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in dictionary.filter(
                (category) => category.dic_group_key === 'class_major'
              )"
              :key="index"
              :label="item.dic_name"
              :value="item.dic_id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="教学老师" prop="cls_stf_id_teacher">
          <el-select
            v-model="editor.mode.cls_stf_id_teacher"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in staffList.filter(
                (item) => item.stf_category === 4
              )"
              :key="index"
              :label="item.stf_name"
              :value="item.stf_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教务老师" prop="cls_stf_id_admin">
          <el-select
            v-model="editor.mode.cls_stf_id_admin"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in staffList.filter(
                (item) => item.stf_category === 5
              )"
              :key="index"
              :label="item.stf_name"
              :value="item.stf_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="就业老师" prop="cls_stf_id_job">
          <el-select v-model="editor.mode.cls_stf_id_job" placeholder="请选择">
            <el-option
              v-for="(item, index) in staffList.filter(
                (item) => item.stf_category === 6
              )"
              :key="index"
              :label="item.stf_name"
              :value="item.stf_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级备注">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入班级备注..."
            v-model="editor.mode.cls_remark"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="saveInfo">保存</el-button>
        <el-button @click="editor.isEditor = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 开课 -->
    <el-dialog
      :visible.sync="editorBegin.isEditorBegin"
      width="40%"
      :modal="false"
    >
      <p slot="title" class="title active">
        开班
      </p>
      <el-form
        label-width="100px"
        ref="ruleFormRoom"
        class="demo-ruleForm"
        :model="editorBegin.mode"
        :rules="editorBegin.rules"
        status-icon
      >
        <el-form-item label="教室" prop="cls_clsr_id">
          <el-select
            v-model="editorBegin.mode.cls_clsr_id"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in classroomList"
              :key="index"
              :label="item.clsr_name"
              :value="item.clsr_id"
              v-show="!item.clsr_occupy"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="okSelectRoom">确定</el-button>
        <el-button @click.native="editorBegin.isEditorBegin = false"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ClassApi } from "@/util/api.js";
export default {
  name: "Class",
  data() {
    return {
      search: {
        cls_name: null,
        cls_dic_id_major: 0,
        cls_status: 0,
      },
      pagination: {
        total: 0,
        pageSize: 5,
        currentPage: 1,
      },
      classList: [], //班级数据
      dictionary: [], //字典映射
      staffList: [], //员工数据
      classroomList: [], //教室数据
      timer: null,
      timerAdd: null,
      allStatus: [
        {
          id: 1,
          name: "- 所有 -",
          cls_status: 0,
        },
        {
          id: 2,
          name: "开课中",
          cls_status: 1,
        },
        {
          id: 3,
          name: "未开课",
          cls_status: 2,
        },
        {
          id: 4,
          name: "结课",
          cls_status: 3,
        },
      ],
      editorBegin: {
        isEditorBegin: false,
        mode: {
          cls_id: "",
          cls_clsr_id: null,
        },
        rules: {
          cls_clsr_id: [
            { required: true, message: "请选择教室", trigger: "change" },
          ],
        },
      },
      editor: {
        isEditor: false,
        isMode: true,
        mode: {
          cls_id: 0,
          cls_name: "",
          cls_dic_id_major: "",
          cls_clsr_id: null,
          cls_stf_id_teacher: "",
          cls_stf_id_admin: "",
          cls_stf_id_job: "",
          cls_begin: null,
          cls_end: null,
          cls_remark: null,
        },
        rules: {
          cls_name: [
            {
              validator: (rule, value, callback) => {
                if (value === "") callback(new Error("请输入班级名称"));
                else {
                  if (this.editor.isMode) {
                    if (this.timerAdd) clearTimeout(this.timerAdd);
                    this.timerAdd = setTimeout(() => {
                      this.$http({
                        url: "/class/valid_name",
                        method: "post",
                        data: {
                          cls_name: value,
                        },
                      }).then((res) => {
                        !res
                          ? callback()
                          : callback(new Error("该名称已使用!"));
                      });
                    }, 1000);
                  }else{
                    callback();
                  }
                }
              },
              trigger: "change",
            },
          ],
          cls_dic_id_major: [
            {
              required: true,
              message: "请选择班级专业",
              trigger: "change",
            },
          ],
          cls_stf_id_teacher: [
            {
              required: true,
              message: "请选择教学老师",
              trigger: "change",
            },
          ],
          cls_stf_id_admin: [
            {
              required: true,
              message: "请选择教务老师",
              trigger: "change",
            },
          ],
          cls_stf_id_job: [
            {
              required: true,
              message: "请选择就业老师",
              trigger: "change",
            },
          ],
        },
      },
    };
  },
  async created() {
    // 分页查询班级信息
    this.getClass(true);
    // 请求字典
    this.getDictionary();
    //请求所有员工信息
    this.getStaff();
    //请求所有教室
    this.getClassRoom();
  },
  methods: {
    initRuleFormRoom() {
      if (this.$refs.ruleFormRoom) this.$refs.ruleFormRoom.resetFields();
    },
    okSelectRoom() {
      // 开班--选择教室
      this.$refs.ruleFormRoom
        .validate()
        .then(() => {
          //验证成功
          this.$http({
            url: "/class/begin",
            method: "post",
            data: {
              ...this.editorBegin.mode,
            },
          }).then((res) => {
            let rooItem = this.classList.find(
              (item) => item.cls_id === this.editorBegin.mode.cls_id
            );
            // 开启占用
            this.classroomList.find(
              (item) => item.clsr_id === this.editorBegin.mode.cls_clsr_id
            ).clsr_occupy = 1;
            rooItem.cls_begin = res;
            rooItem.cls_clsr_id = this.editorBegin.mode.cls_clsr_id;
            console.log("开班成功:", res);
            this.$message({
              type: "success",
              message: "开班成功",
            });
            this.editorBegin.isEditorBegin = false;
          });
        })
        .catch((err) => {
          // 验证失败
        });
    },
    beginClass(index, row) {
      // 开课
      this.$confirm("确定要开课吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.initRuleFormRoom();
          this.editorBegin.isEditorBegin = true;
          this.editorBegin.mode.cls_id = row.cls_id;
          this.editorBegin.mode.cls_clsr_id = null;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    endClass(index, row) {
      // 结课
      this.$confirm("确定要结课吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: "/class/end",
            method: "post",
            data: {
              ...row,
            },
          }).then((res) => {
            //返回一个结课时间
            console.log("结课:", res);
            this.classList.find(
              (item) => item.cls_id === row.cls_id
            ).cls_end = res;
            // 解除占用教室
            this.classroomList.find(
              (item) => item.clsr_id === row.cls_clsr_id
            ).clsr_occupy = 0;
            this.$message({
              type: "success",
              message: "结课成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    initForm() {
      // 初始化表单
      if (this.$refs.ruleForm) this.$refs.ruleForm.resetFields();
    },
    saveInfo() {
      // 保存
      this.$refs.ruleForm
        .validate()
        .then(() => {
          //验证通过
          if (this.editor.isMode) {
            //新增
            this.$http({
              url: "/class/add",
              method: "post",
              data: {
                ...this.editor.mode,
              },
            }).then((res) => {
              this.editor.mode.cls_id = res;
              this.classList.push({ ...this.editor.mode });
            });
            this.$message({
              message: "新增成功",
              type: "success",
            });
          } else {
            //修改
            this.$http({
              url: "/class/update",
              method: "post",
              data: {
                ...this.editor.mode,
              },
            }).then(() => {
              this.classList.splice(
                this.classList.findIndex(
                  (item) => item.cls_id === this.editor.mode.cls_id
                ),
                1,
                { ...this.editor.mode }
              );
              this.$message({
                message: "修改成功",
                type: "success",
              });
            });
          }
          this.editor.isEditor = false;
        })
        .catch(() => {
          //验证失败
        });
    },
    beforeAdd() {
      // 新增
      this.initForm();
      this.editor.isEditor = true;
      this.editor.isMode = true;

      this.editor.mode.cls_id = 0;
      this.editor.mode.cls_name = "";
      this.editor.mode.cls_clsr_id = null;
      this.editor.mode.cls_stf_id_teacher = "";
      this.editor.mode.cls_stf_id_admin = "";
      this.editor.mode.cls_stf_id_job = "";
      this.editor.mode.cls_dic_id_major = null;
      this.editor.mode.cls_begin = null;
      this.editor.mode.cls_end = null;
      this.editor.mode.cls_remark = null;
    },
    beginUpdate(index, row) {
      // 修改
      this.initForm();
      this.editor.isEditor = true;
      this.editor.isMode = false;
      this.editor.mode = { ...row };
    },
    delayGetClass() {
      // 搜索框延迟查询数据
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.getClass(true);
      }, 1000);
    },
    getClassRoom() {
      this.$http({
        url: "/classroom/all",
        methods: "get",
      }).then((res) => {
        console.log("班级信息:", res);
        this.classroomList = res;
      });
    },
    // 员工
    getStaff() {
      this.$http({
        url: "/staff/listbycategory/all",
        method: "get",
      }).then((res) => {
        console.log("所有员工数据:", res);
        this.staffList = res;
      });
    },
    // 班级
    async getClass(isInit = true) {
      if (isInit) {
        this.pagination.currentPage = 1;
      }
      let data = await ClassApi.getClass({
        ...this.search,
        begin: (this.pagination.currentPage - 1) * this.pagination.pageSize,
        pageSize: this.pagination.pageSize,
      });
      console.log("分页查询班级信息:", data);
      let { total, list } = data;
      this.classList = list;
      this.pagination.total = total;

      // return Promise.resolve();
    },
    getDictionary() {
      this.$http({
        url: "/dictionary/all",
        method: "get",
      }).then((res) => {
        console.log("所有字典数据:", res);
        this.dictionary = res;
      });
    },
  },
};
</script>

<style lang="stylus" scoped>
.page-wrap
  position absolute
  top 0
  left 0
  right 0
  bottom 0
  display flex
  flex-direction column
  .el-form
    flex-shrink 0
    .el-form-item
      &.btn-wrap
        float right
  .el-table
    flex-grow 1
    .cell
      .noRemark
        color #ccc

  .el-pagination
    flex-shrink 0
  .el-dialog
    .title
      padding 10px 30px
      font-size 18px
      color white
      background-color #F56C6C
      &.active
        background-color #67C23A
</style>
